﻿var debug = true;

(function($) {
    jQuery.fn.inspiraGrid = function(filterUrl, caption, rowSelectFormatString, colNames, colModel) {
        var element = this;
        configureGrid(element, filterUrl, caption, rowSelectFormatString, colNames, colModel);
        return this;
    };
})(jQuery);

function configureGrid(element, jqGridFilterUrl, jqGridCaption, jqGridRowSelectFormatString, colNames, colModel) {

    var gridId = "#" + element.parent().parent().attr("id");
    var pagerId = element.parent().parent().attr("id") + "GridPager";

    $.blockUI.defaults.overlayCSS.opacity = 0.3;
    $.blockUI.defaults.css.border = "none";
    $.blockUI.defaults.css.background = "none";
    $.blockUI.defaults.css.width = "32px";
    $.blockUI.defaults.message = "<span class='ajaxloading'>&nbsp;</span>";    
    
    $(gridId + ' div.GridPager').attr("id", pagerId);

    jQuery(gridId).find(".GridFiltersHeader").click(function() {
        jQuery(this).next().toggle("slide", { direction: "up" }, 200);
        jQuery(this).toggleClass("ui-corner-all").toggleClass("ui-corner-top");
        jQuery(this).find("span.filtericon").toggleClass("ui-icon-carat-1-e").toggleClass("ui-icon-carat-1-s");
        
        return false;
    });

    $(gridId + " form.FormFilters").submit(function(event) {
        $.post(jqGridFilterUrl + "FilterParams", $(this).find("input, select").serializeArray(),
        function(data) {
            //alert("Data Loaded: " + data);
            //$(gridId).find("div.GridFilter").unblock();
            $(gridId + " table.GridTable").jqGrid('setGridParam', { url: jqGridFilterUrl + "JqGridFilter?&conditions=" + data, page: 1 }).trigger("reloadGrid");
        });
        event.preventDefault();
        $jQuery(gridId).find('div.Grid').block();
    });

    element.jqGrid({
        url: jqGridFilterUrl + "JqGridFilter",
        datatype: "json",
        hidegrid: false,
        height: "100%",
        altRows: true,
        autowidth: true,
        id: 'Id',
        colNames: colNames,
        colModel: colModel,
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: pagerId,
        sortname: "id",
        sortorder: "desc",
        caption: jqGridCaption,
        viewrecords: true,
        loadui: "disable",
        onSelectRow: function(id) {
            var ret = element.jqGrid('getRowData', id);
            //mensagem(formatString(jqGridRowSelectFormatString, ret));

            var offset = jQuery(gridId).find('tr.ui-state-highlight').find('span.gridactions').offset();
            var position = jQuery(gridId).find('tr.ui-state-highlight').find('span.gridactions').position();
            var toolsWidth = jQuery(gridId).find('div.GridTools').width();
            var toolsHeight = jQuery(gridId).find('div.GridTools').height();
            var tablePosition = jQuery(gridId).find('table.GridTable').offset();
            var gridPosition = jQuery(gridId).find('div.ui-jqgrid').offset();

            //alert(tablePosition.top + ' ' + gridPosition.top);

            jQuery(gridId).find('div.GridTools').hide();
            //jQuery(gridId).find('div.GridTools').css({ 'top': (offset.top - 73 - toolsHeight), 'left': (offset.left - 35 - toolsWidth) });
            jQuery(gridId).find('div.GridTools').css({ 'top': (tablePosition.top - gridPosition.top + position.top - 6), 'left': (position.left - 104) });
            jQuery(gridId).find('div.GridTools').find('.btnApagar').click(function() { deleteItem(id) });
            jQuery(gridId).find('div.GridTools').find('a.btnEditar').attr('href', jqGridFilterUrl + 'Edit/' + ret.ID);

            jQuery(gridId).find('div.GridTools').show("slide", { direction: "right" }, 100);
            //alert(jQuery('tr.ui-state-highlight').find('span.gridactions').offset());
        },
        gridComplete: function() {
            var ids = element.jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                var cl = ids[i];

                element.jqGrid('setRowData', ids[i], { Actions: '<span class="gridactions">&nbsp;</span>' });
            }
        },
        beforeRequest: function() {
            jQuery(gridId).find('div.GridTools').hide();
            jQuery(gridId).find('div.Grid').block();
        },
        loadComplete: function() {
            element.jqGrid('setGridWidth', jQuery(gridId).width());
            jQuery(gridId).find('div.Grid').unblock();
        },
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            id: "0"
        }
    });
    element.jqGrid('navGrid', pagerId, { edit: false, add: false, del: false, search: false });

    /*jQuery(gridId).find('div.GridTools').find('a.btnEditar').overlay({
        expose: '#000',
        onBeforeLoad: function() {

            // grab wrapper element inside content
            var wrap = this.getContent().find(".contentWrap");

            // load the page specified in the trigger
            wrap.load(this.getTrigger().attr("href"));
        }
    });*/
    jQuery(gridId).find('input.datepicker').datepicker($.datepicker.regional['pt-BR']).datepicker('option', 'showAnim', 'fadeIn');
}

function formatString(stringFormat, obj) {
    return stringFormat;
}

function inspiraLog(str) {
    if (typeof (console) !== "undefined" && debug) {
        console.log(str);
    }
}


function deleteItem(id) {
    jQuery("#dialog-confirm").dialog({
        resizable: false,
        height: 140,
        modal: true,
        buttons: {
            'Apagar': function() {
                jQuery("#GridTable").jqGrid('delRowData', id);
                jQuery("#GridTools").hide();
                jQuery(this).dialog('close');
                mensagem("Apagado com sucesso");
            },
            'Cancelar': function() {
                jQuery(this).dialog('close');
                erro("Cancelado");
            }
        }
    });
}
function mensagem(msg) {
    jQuery.jGrowl.defaults.position = 'bottom-right';
    jQuery.jGrowl('<span class="ui-icon ui-icon-info fl" style="margin-right:10px;"> </span>' + msg, { header: '' });
}
function erro(msg) {
    jQuery.jGrowl.defaults.position = 'bottom-right';
    jQuery.jGrowl('<span class="ui-icon ui-icon-alert fl" style="margin-right:10px;"> </span>' + msg, { header: '', theme: 'ui-state-error ' });
}